package server

import (
	"fmt"
	"net"
)

type ConnSet struct {
	conns map[connID]net.Conn
}

type connID struct {
	remoteIP   string
	remotePort int
	localIP    string
	localPort  int
}

func extractConnID(conn net.Conn) connID {
	remoteAddr := conn.RemoteAddr().(*net.TCPAddr)
	localAddr := conn.LocalAddr().(*net.TCPAddr)
	return connID{
		remoteIP:   remoteAddr.IP.String(),
		remotePort: remoteAddr.Port,
		localIP:    localAddr.IP.String(),
		localPort:  localAddr.Port,
	}
}

func (s *ConnSet) Add(conn net.Conn) error {
	id := extractConnID(conn)
	if _, ok := s.conns[id]; ok {
		return fmt.Errorf("duplicate connection %v", conn)
	}
	s.conns[id] = conn
	return nil
}
func NewConnSet() *ConnSet {
	return &ConnSet{
		conns: make(map[connID]net.Conn),
	}

}
